using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;

using Framework;

namespace SchemaMonitor
{
    [Serializable()]
    public partial class CSchema : CBaseDynamic, IComparable<CSchema>
    {
        #region Constructors
        //Public (Copy Constructor)
        public CSchema(CSchema original, CDataSrc target)
        {
            //Database Connection
            m_dataSrc = target;

            //Copy fields
            _schemaName = original.SchemaName;
            _schemaUrlBase = original.SchemaUrlBase;
            _schemaUrlGetToken = original.SchemaUrlGetToken;
            _schemaApiClientId = original.SchemaApiClientId;
            _schemaApiTokenTemp = original.SchemaApiTokenTemp;
            _schemaApiTokenEncr = original.SchemaApiTokenEncr;
            _schemaApiSecretTemp = original.SchemaApiSecretTemp;
            _schemaApiSecretEncr = original.SchemaApiSecretEncr;
            _schemaCreated = original.SchemaCreated;
            _schemaUpdated = original.SchemaUpdated;
        }

        //Protected (Datareader/Dataset)
        protected CSchema(CDataSrc dataSrc, IDataReader dr) : base(dataSrc, dr) {}
        protected CSchema(CDataSrc dataSrc, DataRow     dr) : base(dataSrc, dr) {}
        #endregion

        #region Default Values
        protected override void InitValues_Auto()
        {
            //Null-Equivalent values (except String.Empty, as nulls tend to be inconvenient for string types)
            _schemaId = int.MinValue;
            _schemaName = string.Empty;
            _schemaUrlBase = string.Empty;
            _schemaUrlGetToken = string.Empty;
            _schemaApiClientId = string.Empty;
            _schemaApiTokenTemp = string.Empty;
            _schemaApiTokenEncr = new byte[]{};
            _schemaApiSecretTemp = string.Empty;
            _schemaApiSecretEncr = new byte[]{};
            _schemaCreated = DateTime.MinValue;
            _schemaUpdated = DateTime.MinValue;
        }
        #endregion

        #region Members
        protected int _schemaId;
        protected string _schemaName;
        protected string _schemaUrlBase;
        protected string _schemaUrlGetToken;
        protected string _schemaApiClientId;
        protected string _schemaApiTokenTemp;
        protected byte[] _schemaApiTokenEncr;
        protected string _schemaApiSecretTemp;
        protected byte[] _schemaApiSecretEncr;
        protected DateTime _schemaCreated;
        protected DateTime _schemaUpdated;
        #endregion

        #region Properties - Column Values
        //Primary Key Column (ReadOnly)
        public int SchemaId    {   get { return _schemaId;   } }

        //Table Columns (Read/Write)
        public string SchemaName    {   get { return _schemaName; } set { _schemaName = value; }    }
        public string SchemaUrlBase    {   get { return _schemaUrlBase; } set { _schemaUrlBase = value; }    }
        public string SchemaUrlGetToken    {   get { return _schemaUrlGetToken; } set { _schemaUrlGetToken = value; }    }
        public string SchemaApiClientId    {   get { return _schemaApiClientId; } set { _schemaApiClientId = value; }    }
        public string SchemaApiTokenTemp    {   get { return _schemaApiTokenTemp; } set { _schemaApiTokenTemp = value; }    }
        public byte[] SchemaApiTokenEncr    {   get { return _schemaApiTokenEncr; } set { _schemaApiTokenEncr = value; }    }
        public string SchemaApiSecretTemp    {   get { return _schemaApiSecretTemp; } set { _schemaApiSecretTemp = value; }    }
        public byte[] SchemaApiSecretEncr    {   get { return _schemaApiSecretEncr; } set { _schemaApiSecretEncr = value; }    }
        public DateTime SchemaCreated    {   get { return _schemaCreated; } set { _schemaCreated = value; }    }
        public DateTime SchemaUpdated    {   get { return _schemaUpdated; } set { _schemaUpdated = value; }    }

        //View Columns (ReadOnly)

        #endregion

        #region MustOverride Methods
        //Schema Information
        public const string TABLE_NAME      = "Schemas";
        public const string VIEW_NAME       = "";         //Used to override this.ViewName { get }
        public const string ORDER_BY_COLS   = "SchemaName";   //See the CompareTo method below (Sql-based sorting should match In-Memory sorting)
        public const string SORTING_COLUMN  = "";
        public override string TableName {    get { return TABLE_NAME; } }
        protected override string OrderByColumns {    get { return ORDER_BY_COLS; } }

        //CompareTo Interface (Default Sort Order)
        public int CompareTo(CSchema other) {   return this.SchemaName.CompareTo(other.SchemaName) ;  }

        //Primary Key Information
        public const string PRIMARY_KEY_NAME = "SchemaId";
        protected override bool InsertPrimaryKey {  get { return false;    }   }
        protected override string PrimaryKeyName {  get { return PRIMARY_KEY_NAME;    }    }
        protected override object PrimaryKeyValue 
        {
              get { return _schemaId; }
              set { _schemaId = (int)value; }
        }

        //Factory Methods - Object
        protected override CBase MakeFrom(DataRow row)      {   return new CSchema(this.DataSrc, row);  }
        protected override CBase MakeFrom(IDataReader dr)   {   return new CSchema(this.DataSrc, dr);   }

        //Factory Methods - List
        protected override IList MakeList()                 {   return new CSchemaList();               }
        protected override IList MakeList(int capacity)     {   return new CSchemaList(capacity);       }

        //Convert from ADO to .Net
        protected override void ReadColumns(IDataReader dr)
        {
            _schemaId = CAdoData.GetInt(dr, "SchemaId");
            _schemaName = CAdoData.GetStr(dr, "SchemaName");
            _schemaUrlBase = CAdoData.GetStr(dr, "SchemaUrlBase");
            _schemaUrlGetToken = CAdoData.GetStr(dr, "SchemaUrlGetToken");
            _schemaApiClientId = CAdoData.GetStr(dr, "SchemaApiClientId");
            _schemaApiTokenTemp = CAdoData.GetStr(dr, "SchemaApiTokenTemp");
            _schemaApiTokenEncr = CAdoData.GetBytes(dr, "SchemaApiTokenEncr");
            _schemaApiSecretTemp = CAdoData.GetStr(dr, "SchemaApiSecretTemp");
            _schemaApiSecretEncr = CAdoData.GetBytes(dr, "SchemaApiSecretEncr");
            _schemaCreated = CAdoData.GetDate(dr, "SchemaCreated");
            _schemaUpdated = CAdoData.GetDate(dr, "SchemaUpdated");
        }
        protected override void ReadColumns(DataRow dr)
        {
            _schemaId = CAdoData.GetInt(dr, "SchemaId");
            _schemaName = CAdoData.GetStr(dr, "SchemaName");
            _schemaUrlBase = CAdoData.GetStr(dr, "SchemaUrlBase");
            _schemaUrlGetToken = CAdoData.GetStr(dr, "SchemaUrlGetToken");
            _schemaApiClientId = CAdoData.GetStr(dr, "SchemaApiClientId");
            _schemaApiTokenTemp = CAdoData.GetStr(dr, "SchemaApiTokenTemp");
            _schemaApiTokenEncr = CAdoData.GetBytes(dr, "SchemaApiTokenEncr");
            _schemaApiSecretTemp = CAdoData.GetStr(dr, "SchemaApiSecretTemp");
            _schemaApiSecretEncr = CAdoData.GetBytes(dr, "SchemaApiSecretEncr");
            _schemaCreated = CAdoData.GetDate(dr, "SchemaCreated");
            _schemaUpdated = CAdoData.GetDate(dr, "SchemaUpdated");
        }

        //Parameters for Insert/Update    
        protected override CNameValueList ColumnNameValues()
        {
            CNameValueList data = new CNameValueList();
            data.Add("SchemaId", CAdoData.NullVal(_schemaId));
            data.Add("SchemaName", CAdoData.NullVal(_schemaName));
            data.Add("SchemaUrlBase", CAdoData.NullVal(_schemaUrlBase));
            data.Add("SchemaUrlGetToken", CAdoData.NullVal(_schemaUrlGetToken));
            data.Add("SchemaApiClientId", CAdoData.NullVal(_schemaApiClientId));
            data.Add("SchemaApiTokenTemp", CAdoData.NullVal(_schemaApiTokenTemp));
            data.Add("SchemaApiTokenEncr", CAdoData.NullVal(_schemaApiTokenEncr));
            data.Add("SchemaApiSecretTemp", CAdoData.NullVal(_schemaApiSecretTemp));
            data.Add("SchemaApiSecretEncr", CAdoData.NullVal(_schemaApiSecretEncr));
            data.Add("SchemaCreated", CAdoData.NullVal(_schemaCreated));
            data.Add("SchemaUpdated", CAdoData.NullVal(_schemaUpdated));
            return data;
        }
        #endregion

        #region Queries - SelectAll/SelectWhere (inherited methods, cast only)
        //Normally used to load the cache
        public    new CSchemaList SelectAll()                                                                           {   return (CSchemaList)base.SelectAll();        }
        public    new CSchemaList SelectAll(string orderBy)                                                             {   return (CSchemaList)base.SelectAll(orderBy); }

        //Sometimes use a custom query to load the cache
        protected new CSchemaList SelectWhere(string colName, ESign sign, object colValue)                              {   return (CSchemaList)base.SelectWhere(colName, sign, colValue);                  }
        protected new CSchemaList SelectWhere(CCriteria where)                                                          {   return (CSchemaList)base.SelectWhere(where);                                    }
        protected new CSchemaList SelectWhere(CCriteriaList where)                                                      {   return (CSchemaList)base.SelectWhere(where);                                    }
        protected new CSchemaList SelectWhere(CCriteriaList where, string tableOrJoin)                                  {   return (CSchemaList)base.SelectWhere(where, tableOrJoin, this.OrderByColumns);  }
        protected new CSchemaList SelectWhere(CCriteriaList where, string tableOrJoin, string orderBy)                  {   return (CSchemaList)base.SelectWhere(where, tableOrJoin, orderBy);              }
        [Obsolete("Arbitrary where-clause is not necessary portable or safe from sql injection attacks. Consider using the parameterised query interfaces (or a stored proc)")]
        protected new CSchemaList SelectWhere(string unsafeWhereClause)                                                 {   return (CSchemaList)base.SelectWhere(unsafeWhereClause);                        }
        protected     CSchemaList SelectById(int schemaId)                                               {   return (CSchemaList)base.SelectById(schemaId);                    }
        protected     CSchemaList SelectByIds(List<int> ids)                                         {   return (CSchemaList)base.SelectByIds(ids);                                      }

        //Select Queries - Paged
        protected new CSchemaList SelectAll(  CPagingInfo pi)                                               {    return (CSchemaList)base.SelectAll(  pi);                          }
        protected new CSchemaList SelectWhere(CPagingInfo pi, string name, ESign sign, object value)        {    return (CSchemaList)base.SelectWhere(pi, name, sign, value);       }
        protected new CSchemaList SelectWhere(CPagingInfo pi, CCriteria criteria)                           {    return (CSchemaList)base.SelectWhere(pi, criteria);                }
        protected new CSchemaList SelectWhere(CPagingInfo pi, CCriteriaList criteria)                       {    return (CSchemaList)base.SelectWhere(pi, criteria);                }
        protected new CSchemaList SelectWhere(CPagingInfo pi, CCriteriaList criteria, string viewOrJoin)    {    return (CSchemaList)base.SelectWhere(pi, criteria, viewOrJoin);    }

        //Select Queries - Transactional (Internal scope for use in cascade deletes)
        internal new CSchemaList SelectAll(                                                                                           IDbTransaction tx)  {    return (CSchemaList)base.SelectAll(                                                 tx);    }
        internal new CSchemaList SelectAll(string orderBy,                                                                            IDbTransaction tx)  {    return (CSchemaList)base.SelectAll(orderBy,                                         tx);    }
        internal new CSchemaList SelectWhere(string columnName,               object columnValue,                                     IDbTransaction tx)  {    return (CSchemaList)base.SelectWhere(columnName,              columnValue,          tx);    }
        internal new CSchemaList SelectWhere(string columnName,   ESign sign, object columnValue,                                     IDbTransaction tx)  {    return (CSchemaList)base.SelectWhere(columnName,    sign,     columnValue,          tx);    }
        internal new CSchemaList SelectWhere(                             CCriteria     criteria,                                     IDbTransaction tx)  {    return (CSchemaList)base.SelectWhere(               criteria,                       tx);    }
        internal new CSchemaList SelectWhere(                             CCriteriaList criteria,                                     IDbTransaction tx)  {    return (CSchemaList)base.SelectWhere(               criteria,                       tx);    }
        internal new CSchemaList SelectWhere(                             CCriteriaList criteria, string tableOrJoin,                 IDbTransaction tx)  {    return (CSchemaList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal new CSchemaList SelectWhere(                             CCriteriaList criteria, string tableOrJoin, string orderBy, IDbTransaction tx)  {    return (CSchemaList)base.SelectWhere(               criteria, tableOrJoin,          tx);    }
        internal     CSchemaList SelectById(int schemaId,                                                              IDbTransaction tx)  {    return (CSchemaList)base.SelectById(schemaId,                         tx);    }
        internal     CSchemaList SelectByIds(List<int> ids,                                                        IDbTransaction tx)  {    return (CSchemaList)base.SelectByIds(ids,                                           tx);    }

        //Select Queries - Stored Procs
        protected new CSchemaList MakeList(string storedProcName,                           IDbTransaction txOrNull)    {   return (CSchemaList)base.MakeList(storedProcName,             txOrNull);  }
        protected new CSchemaList MakeList(string storedProcName, object[] parameters,      IDbTransaction txOrNull)    {   return (CSchemaList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CSchemaList MakeList(string storedProcName, CNameValueList parameters,IDbTransaction txOrNull)    {   return (CSchemaList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CSchemaList MakeList(string storedProcName, List<object> parameters,  IDbTransaction txOrNull)    {   return (CSchemaList)base.MakeList(storedProcName, parameters, txOrNull);  }
        protected new CSchemaList MakeList(string storedProcName, int param1,               IDbTransaction txOrNull)    {   return (CSchemaList)base.MakeList(storedProcName, param1,     txOrNull);  }
        protected new CSchemaList MakeList(string storedProcName, string param1,            IDbTransaction txOrNull)    {   return (CSchemaList)base.MakeList(storedProcName, param1,     txOrNull);  }

        //Query Results
        protected new CSchemaList MakeList(DataSet              ds) { return (CSchemaList)base.MakeList(ds);        }
        protected new CSchemaList MakeList(DataTable            dt) { return (CSchemaList)base.MakeList(dt);        }
        protected new CSchemaList MakeList(DataRowCollection  rows) { return (CSchemaList)base.MakeList(rows);      }
        protected new CSchemaList MakeList(IDataReader          dr) { return (CSchemaList)base.MakeList(dr);        }
        protected new CSchemaList MakeList(object           drOrDs) { return (CSchemaList)base.MakeList(drOrDs);    }
        protected new CSchemaList MakeList(byte[]             gzip) { return (CSchemaList)base.MakeList(gzip);      }
        #endregion

        #region Queries - SelectBy[FK] (user-nominated fk/bool columns)
        //Note: These methods should only be used for cascade-deletes, or initialising the cache. Use CSchema.Cache.GetBy... for reqular queries

        //Non-Paged
        protected CSchemaList SelectByName(string schemaName)    {    return SelectWhere(new CCriteriaList("SchemaName", schemaName));    }

        //Paged
        protected CSchemaList SelectByName(CPagingInfo pi, string schemaName)    {    return SelectWhere(pi, new CCriteriaList("SchemaName", schemaName));    }

        //Count
        protected int SelectCountByName(string schemaName)   {   return SelectCount(new CCriteriaList("SchemaName", schemaName));     }

        //Transactional
        internal CSchemaList SelectByName(string schemaName, IDbTransaction tx)    {    return SelectWhere(new CCriteriaList("SchemaName", schemaName), tx);    }
        #endregion

        #region Static - Cache Implementation
        public static CSchemaList Cache
        {
            get
            {
                CSchemaList cache = (CSchemaList)CCache.Get(CACHE_KEY);
                if (cache == null)
                {
                    lock (typeof(CSchemaList))
                    {
                        cache = (CSchemaList)CCache.Get(CACHE_KEY);
                        if (cache == null)
                        {
                            cache = LoadCache();
                            CSchema.Cache = cache;
                        }
                    }
                }
                return cache;
            }
            set
            {
                SetCache(value);   //Not locked, because cache gets cleared at anytime anyway
            }
        }

        //Change Management:
        //Clone, modify, and then replace the cache (threadsafe for anything iterating the collection)
        //Note that internal indices are dicarded each time unless handled in constructor and add/remove overrides
        protected override void CacheDelete()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CSchemaList))
            {
                CSchemaList temp = new CSchemaList(Cache);
                int size = temp.Count;
                temp.Remove(this);
                if (size == temp.Count) //Remove might fail if cache was refreshed with new instances. Use old index
                    temp.Remove(CacheGetById(temp));
                Cache = temp;
            }
        }
        protected override void CacheInsert()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CSchemaList))
            {
                CSchemaList temp = new CSchemaList(Cache);
                temp.Add(this);
                SetCache(temp);
            }
        }
        protected override void CacheUpdate()
        {
            if (CacheIsNull)
                return;

            lock (typeof(CSchemaList))
            {
                CSchemaList temp = new CSchemaList(Cache);
                if (!temp.Contains(this))
                {
                    temp.Remove(CacheGetById(temp));
                    temp.Add(this);
                }
                SetCache(temp);
            }
        }
        protected override void CacheClear()
        {
            SetCache(null);
        }
        protected static bool CacheIsNull
        {
            get
            {
                return null == CCache.Get(CACHE_KEY);
            }
        }
        #endregion
        #region ToXml
        protected override void ToXml_Autogenerated(System.Xml.XmlWriter w)
        {
            Store(w, "SchemaId", this.SchemaId);
            Store(w, "SchemaName", this.SchemaName);
            Store(w, "SchemaUrlBase", this.SchemaUrlBase);
            Store(w, "SchemaUrlGetToken", this.SchemaUrlGetToken);
            Store(w, "SchemaApiClientId", this.SchemaApiClientId);
            Store(w, "SchemaApiTokenTemp", this.SchemaApiTokenTemp);
            Store(w, "SchemaApiTokenEncr", this.SchemaApiTokenEncr);
            Store(w, "SchemaApiSecretTemp", this.SchemaApiSecretTemp);
            Store(w, "SchemaApiSecretEncr", this.SchemaApiSecretEncr);
            Store(w, "SchemaCreated", this.SchemaCreated);
            Store(w, "SchemaUpdated", this.SchemaUpdated);
        }
        #endregion

    }
}
